
const { ccclass, property } = cc._decorator;

@ccclass
export default class ASingleton extends cc.Component {

    protected SingletonInstance: any = null;
    protected static Count: number = 0;

    protected Load() { }
    protected Destroy() { }
    protected get isPersist(): boolean { return false; }

    protected EnableLog = true;
    protected log(...data: any) {
        if (this.EnableLog) {
            if (cc.sys.isNative) {
                console.log(...data);
            } else {
                console.log(`%c[${this.constructor.name}]`, 'color: #43bb88', ...data);
            }
        }
    }

    protected SingletonRegister<T extends ASingleton>(obj: { prototype: T }) {
        if (obj["mInstance"] != null) {
            if (obj["mInstance"] == this) {
                this.log("重复注册");
                return;
            }
            this.node.destroy();
        } else {
            if (this.isPersist) {
                cc.game.addPersistRootNode(this.node);
            }
            obj["mInstance"] = this;
            this.SingletonInstance = obj;
            this.Load();
        }
    }

    protected onLoad(): void {
        this.SingletonRegister(this.constructor);
        ASingleton.Count++;
        this.log("onLoad", ASingleton.Count);
    }

    protected onDestroy(): void {
        if (this.SingletonInstance && this.SingletonInstance["mInstance"] == this) {
            this.SingletonInstance["mInstance"] = null;
            this.Destroy();
        }
    }
}
